<template>
  <el-card shadow="never" class="common-card">
    <template #header>
      <el-row justify="space-between" align="middle">
        <h1>用户管理</h1>
        <el-breadcrumb sepatrator="/">
          <el-breadcrumb-item to="/control">控制台</el-breadcrumb-item>
          <el-breadcrumb-item to="/control/user">用户管理</el-breadcrumb-item>
          <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
      </el-row>
    </template>

    <div class="common-search">
      <el-form :inline="true">
        <el-form-item>
          <el-button type="danger" @click="delBatchByIds"  v-if="delIds.length > 0">批量删除</el-button>
        </el-form-item>
        <el-form-item label="选择审核">
          <el-select style="width: 120px;" v-model.number="queryForm.status" placeholder="选择审核" clearable>
            <el-option :value="1" label="未审核" />
            <el-option :value="2" label="已审核" />
          </el-select>
        </el-form-item>
        <el-form-item label="输入关键字">
          <el-input style="width: 220px;" v-model.trim="queryForm.keyword" placeholder="请输入账号/昵称/手机号" clearable />
        </el-form-item>

        <el-form-item>
          <el-button circle style="background-color: cornflowerblue;">
            <el-icon type="warning" style="color: white;" @click="getUserList">
              <refresh />
            </el-icon>
          </el-button>
        </el-form-item>

      </el-form>
      <el-button type="primary" @click="openDialog()">新增</el-button>
    </div>
    <!-- 表格模块 -->
    <el-table ref="tableRef" v-loading="loading" :data="pageData" style="width: 100%;" stripe border
    @selection-change="onselectionChange">
      <el-table-column type="selection" width="40" />
      <el-table-column label="账号" width="120" prop="userName" />
      <el-table-column label="头像" width="70" #default="scope">
        <el-avatar :size="36" :src="$resolvPath(scope.row.avatar)" />
      </el-table-column>
      <el-table-column label="昵称" prop="nickName" width="100" />
      <el-table-column label="状态" width="90" prop="status" #default="scope">
        <span color="red" v-if="scope.row.status === 1">未审核</span>
        <span color="green" v-else-if="scope.row.status === 2">已审核</span>
      </el-table-column>
      <el-table-column label="性别" prop="gender" width="60" />
      <el-table-column label="手机" prop="phone" width="120" />
      <el-table-column label="邮箱" prop="email" />
      <el-table-column label="创建时间" prop="createTime" #default="scope">
        <span>{{ moment(scope.row.createTime).format('YYYY年MM月DD日') }}</span>
      </el-table-column>

      <el-table-column label="操作" width="150" #default="scope" fixed="right">
        <el-button plain type="primary" size="small" @click="openDialog(scope.row.id)">修改</el-button>
        <el-button plain type="danger" size="small" @click="delById(scope.row.id)">删除</el-button>
      </el-table-column>
    </el-table>


    <template #footer>
      <el-pagination background v-model:current-page="page" v-model:page-size="pageSize"
        :page-sizes="[2, 3, 4, 5, 6, 7, 8]" layout="total, sizes, prev, pager, next, jumper"
        :total="searchData.length" />
    </template>

  </el-card>

  <!-- 弹层 -->
  <Teleport to="body">

    <el-dialog v-model="dialogVisible" :title="`${$editId === 0 ? '新增' : '修改'}用户`" width="500">
      <el-form label-width="80px" :model="form" ref="formRef" :rules="rules">
        <el-form-item label="账号" prop="userName">
          <el-input v-model.trim="form.userName" placeholder="请输入账号" clearable />
        </el-form-item>
        <el-form-item label="昵称" prop="nickName">
          <el-input v-model.trim="form.nickName" placeholder="请输入昵称" clearable />
        </el-form-item>
        <el-form-item label="密码" :prop="$editId === 0 ? 'password' : ''">
          <el-input v-model.trim="form.password" placeholder="请输入密码" clearable />
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="form.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model.trim="form.phone" placeholder="请输入手机号" clearable />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model.trim="form.email" placeholder="请输入邮箱" clearable />
        </el-form-item>
      </el-form>
      <el-form-item label="上传图片" prop="avatar">
        <el-tooltip effect="dark" content="请上传图片" placement="top">
          <el-upload class="uploader" name="file" action="/api/manage/upload"
            :headers="{ 'Authorrization': $authorization }" :show-file-list="false" :on-success="onUploadSuccess"
            style="width: 100px; height: 100px;">
            <img v-if="form.avatar" :src="form.avatar.startsWith('http') ? form.avatar : $baseAdminUrl + form.avatar" >
            <el-icon :size="20" color="#8c939d" v-else>
              <Plus />
            </el-icon>
          </el-upload>
        </el-tooltip>
      </el-form-item>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="onAddOrEditUser">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </Teleport>
</template>

<script lang="ts" setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import { userList, userDel, userBatchDel, userEditOrAdd, userById } from '@/apis/user';
import { ref, reactive, computed } from 'vue'
import type { IUser, IApiResult, FormRulesCallback } from '@/types';
import moment from 'moment';
//查询 - 搜索条件定义
const queryForm = reactive({
  status: '',
  keyword: ''
})
//分页 - 页码定义
const page = ref(1)
const pageSize = ref(4)

//查询 - 加载状态
const loading = ref(false)
const tableData = ref([])


//查询用户列表
const getUserList = async () => {
  try {
    const res = await userList();
    if (res.data.code !== 0) {
      ElMessage.error(res.data.desc);
      return
    }
    tableData.value = res.data.data;
    console.log(tableData.value);
    loading.value = false;
  } catch (err) {
    ElMessage.error(JSON.stringify(err));
  }
}
getUserList();

//定义搜索数据
const searchData = computed(() => {
  const { status, keyword } = queryForm;
  return tableData.value.filter((item: IUser) => {
    return (status ? item.status === Number(status) : true) &&
      (item.userName.includes(keyword) || item.nickName.includes(keyword) || item.phone.includes(keyword) || item.email.includes(keyword));
  })
})

// 获取当前页的数据
const pageData = computed(() => {
  const start = (page.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return searchData.value.slice(start, end)
})

// 获取轮播列表数据

//新增/修改模块
const formRef = ref();
const dialogVisible = ref(false);
const form = reactive<IUser>({
  id: 0,
  email: '',
  gender: '',
  nickName: '',
  phone: '',
  status: 0,
  userName: '',
  avatar: '',
  password: ''
})

const checkphone = (rule:any, value:string, callback:FormRulesCallback) => {
  console.log(rule);
  if(!/^1[34578]\d{9}$/.test(value)){
    callback(new Error('请输入正确的手机号'));
    return
  }
  callback();
}

const rules = reactive({
  userName: { required: true, message: '请输入账号' },
  nickName: { required: true, message: '请输入昵称' },
  phone:[
    { required: true, message: '请输入手机号' },
    {validator:checkphone}
  ],
  password: { required: true, message: '请输入密码' }
})

const $editId = ref(0);

const openDialog = async (editId: number = 0) => {
  $editId.value = editId;
  if (editId) {
    formRef.value?.clearValidate();
    try {
      const res = await userById(editId);
      if (res.data.code !== 0) {
        ElMessage.error(res.data.desc);
        return
      }
      form.id = res.data.data.id;
      form.email = res.data.data.email;
      form.gender = res.data.data.gender;
      form.status = res.data.data.status;
      form.nickName = res.data.data.nickName;
      form.phone = res.data.data.phone;
      form.userName = res.data.data.userName;
      form.avatar = res.data.data.avatar;
      form.password = res.data.data.password;
    } catch (err) {
      ElMessage.error(JSON.stringify(err));
    }
  } else {
    formRef.value?.resetFields();

    formRef.value?.resetFields();
    form.id = 0;
    form.gender = '';
    form.phone = '';
    form.status = 2;
    form.userName = '';
    form.nickName = '';
    form.email = '';
    form.avatar = '';
    form.password = '';
  }
  dialogVisible.value = true;
}

const onAddOrEditUser = async () => {
  try {
    const isValid = await formRef.value.validate();
    if (!isValid) return;
    const res = await userEditOrAdd(form);
    if (res.data.code !== 0) {
      ElMessage.error(res.data.desc);
      return
    }
    ElMessage.success(form.id ? '修改成功' : '新增成功');

    dialogVisible.value = false;
    getUserList();
  } catch (err) {
    if (typeof err === 'string') ElMessage.error(JSON.stringify(err));
    console.error(err);

  }
}




const onUploadSuccess = (res: IApiResult) => {
  if (res.code !== 0) {
    ElMessage.error(res.msg);
    return
  }
  form.avatar = res.data as string;
  ElMessage.success('上传成功');
}


// 删除相关
// 已选择删除的ID列表
const delIds = ref<number[]>([]);
// 当选择项发生变化时更新已选择删除的ID列表
const onselectionChange = (val: IUser[]) => {
    delIds.value = val.map((item: IUser) => item.id) as number[]
}

// 根据ID删除单条轮播信息
const delById = async (id: number) => {
    try {
        const yes = await ElMessageBox.confirm('您确定要删除此条信息？', '提示', { type: 'warning' });
        if (!yes) return;
        const res = await userDel(id);
        if (res.data.code !== 0) {
            ElMessage.error(res.data.desc);
            return
        }
        ElMessage.success('删除成功');
        getUserList();
    } catch (err) {
        ElMessage.error(JSON.stringify(err))
    }
}

// 批量删除选中的轮播信息
const tableRef = ref();
const delBatchByIds = async () => {
    try {
        const yes = await ElMessageBox.confirm('您确定要删除所选信息？', '提示', { type: 'warning' });
        if (!yes) return;
        await userBatchDel(delIds.value);
        ElMessage.success('删除成功');
        getUserList();
    } catch (err) {
        if (err === 'cancel') {
            tableRef.value.clearSelection();
            return;
        }
    }
}
</script>